import { _decorator, Component, Sprite, UITransform } from 'cc'
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager'
import { DIRECTION_ENUM, DIRECTION_ORDER_ENUM, ENTITY_STATE_ENUM, ENTITY_TYPE_ENUM, PARAMS_NAME_ENUM } from '../Enums'
import { PlayerStateMachine } from './../Player/PlayerStateMachine'
import { IEntity } from '../Levels'
const { ccclass, property } = _decorator

export const ANIMATION_SPEED = 1 / 8

@ccclass('EntityManager')
export class EntityManager extends Component {
  currentX: number = 0
  currentY: number = 0
  fsm: PlayerStateMachine
  type: ENTITY_TYPE_ENUM

  private _direction: DIRECTION_ENUM
  private _state: ENTITY_STATE_ENUM

  get direction(): DIRECTION_ENUM {
    return this._direction
  }

  set direction(value: DIRECTION_ENUM) {
    this._direction = value
    this.fsm.setParams(PARAMS_NAME_ENUM.DIRECTION, DIRECTION_ORDER_ENUM[this._direction])
  }

  get state(): ENTITY_STATE_ENUM {
    return this._state
  }

  set state(value: ENTITY_STATE_ENUM) {
    this._state = value
    this.fsm.setParams(this._state, true)
  }

  async init(params: IEntity) {
    const sprite = this.addComponent(Sprite)
    sprite.sizeMode = Sprite.SizeMode.CUSTOM

    const transform = this.addComponent(UITransform)
    transform.setContentSize(TILE_WIDTH * 4, TILE_HEIGHT * 4)

    this.fsm = this.addComponent(PlayerStateMachine)
    await this.fsm.init()

    this.currentX = params.x
    this.currentY = params.x
    this.type = params.type
    this.direction = params.direction
    this.state = params.state
  }

  playerPlace() {
    let x1 = this.currentX * TILE_WIDTH
    let x2 = TILE_WIDTH * 1.5
    let x3 = TILE_WIDTH * 4
    let xCoordinate = x1 - x2 + x3

    let y1 = -this.currentY * TILE_HEIGHT
    let y2 = TILE_HEIGHT * 1.5
    let y3 = TILE_HEIGHT * 10
    let yCoordinate = y1 + y2 - y3

    this.node.setPosition(xCoordinate, yCoordinate)
  }

  update(): void {
    this.playerPlace()
  }
}
